<?php
/**
 * Created by PhpStorm.
 * User: George
 * Date: 2017/9/25
 * Time: 11:06
 */

namespace AdminBundle\Task;

use AdminBundle\Entity\LogContactChat;

/**
 * 聊天发送名片
 * Class ChatToSendCardTask
 * @package AdminBundle\Task
 */
class ChatToSendCardTask extends Task
{
    const SOURCE_TYPE_CARD = 3; //名片好友
    const SOURCE_TYPE_LABOUR = 2; //营销好友

    /**
     * 返回
     * @return null
     */
    public function jsonTask()
    {
        $data = [
            'app' => 'api', 'os' => 'ios', 'deviceid' => $this->task->getDeviceName(),
            'data' =>
                [
                    'token' => $this->task->getAction(),
                    'webchat' => [$this->task->getWebchatUsername(), $this->task->getNote()]
                ]
        ];

        $url = 'http://admin.bjtwtx.com/api/partner/friend/card';
        $json = $this->httpJson($url, $data);

        if ($json == null || $json['code'] != 0) {
            return null;
        }

        // 提取名片好友,设置对话内容
        $dialog = $json['data'];
        $sentences = explode(PHP_EOL, $dialog['sentence']);
        $message = [];
        foreach ($sentences as $sentence) {
            $message[] = ['type' => 'text', 'value' => $sentence, 'delay' => 3];
        }

        $user_id = $this->task->getMethod();

        // 设置名片好友
//        $contactsOfCard = $this->getContacts($user_id, self::SOURCE_TYPE_CARD, $dialog['note']);
        $message[] = ['type' => 'card', 'value' => $dialog['weixinid'], 'delay' => 3];

        // 获取营销好友,填充“名片好友”的聊天内容
        $contacts = $this->getContacts($user_id, self::SOURCE_TYPE_LABOUR, $dialog['note'], 100);
        if (empty($contacts)) {
            // 任务执行失败
            return null;
        }
        $this->logContactChat($contacts, json_encode($dialog));

        $friends = [];
        foreach ($contacts as $contact) {
            $friends[] = [
                'nickname' => $contact['nickname'],
                'username' => $contact['userName'],
                'mobile' => $contact['mobile'],
                'message' => []
            ];
        }
        $chats = ['message' => $message, 'friends' => $friends];
        return json_encode($chats);
    }

    /**
     * 根据微信号选择熟人好友进行聊天
     * 规则：随机
     * @return array
     */
    private function getContacts($user_id, $source_type, $tags, $count = 5)
    {
        $friends = $this->em->getRepository('AdminBundle:BaseWebchatMember')->labourOfChat($user_id, $source_type, $tags, $count);
        if ($friends == null)
            return [];
        return $friends;
    }

    private function logContactChat($contacts, $message)
    {
        $em = $this->em;
        foreach ($contacts as $contact) {
            $logContactChat = new LogContactChat();
            $logContactChat->setCtime(new \DateTime())
                ->setWebchatUserId($this->task->getMethod())
                ->setWebchatUserName($this->task->getWebchatUsername())
                ->setMemberUserId($contact['id'])
                ->setMessage($message);

            $em->persist($logContactChat);
            $em->flush();
            unset($logContactChat);
        }
    }

}